package me.shurufa.fragments;

import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;

import com.google.gson.Gson;
import com.malinskiy.superrecyclerview.SuperRecyclerView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import me.shurufa.R;
import me.shurufa.activities.NewDigestActivity;
import me.shurufa.activities.NewLoginActivity;
import me.shurufa.adapter.BookDigestMeAdapter;
import me.shurufa.db.PersistenceUtils;
import me.shurufa.model.BookDigestListResponse;
import me.shurufa.model.NewComment;
import me.shurufa.model.NewDigest;
import me.shurufa.model.SendCommentResponse;
import me.shurufa.net.API;
import me.shurufa.net.BaseResponse;
import me.shurufa.net.RequestServerTask;
import me.shurufa.utils.Constants;
import me.shurufa.utils.Global;
import me.shurufa.utils.HttpUtil;
import me.shurufa.utils.LogUtils;
import me.shurufa.utils.NetworkUtils;
import me.shurufa.utils.RecyclerViewStateUtils;
import me.shurufa.utils.Utils;
import me.shurufa.widget.LoadingFooter;
import me.shurufa.widget.commentbar.SendCommentBar;
import me.shurufa.widget.pulltorefresh.SrfPtrFrameLayout;
import me.shurufa.widget.recyclerview.EndlessRecyclerOnScrollListener;
import me.shurufa.widget.recyclerview.HeaderAndFooterRecyclerViewAdapter;
import me.shurufa.widget.simpledialog.SimpleDialog;
import me.shurufa.widget.timelineheader.HeaderDigestBarLayout;
import me.shurufa.widget.timelineheader.OnBarItemClickListener;

/**
 * 作者 : andy
 * 日期 : 16/3/9 10:31
 * 邮箱 : andyxialm@gmail.com
 * 描述 : 书摘Fragment
 */
public class MyBookDigestFragment extends BaseListFragment implements View.OnClickListener, AppBarLayout.OnOffsetChangedListener {

    @Bind(R.id.recycler_view)
    SuperRecyclerView recyclerView;

    @Bind(R.id.ptr_refresh)
    SrfPtrFrameLayout ptrRefresh;

    @Bind(R.id.header_digist_bar)
    HeaderDigestBarLayout header_digist_bar;

    @Bind(R.id.scb_comment_bar)
    SendCommentBar scb_comment_bar;

    @Bind(R.id.appbar)
    AppBarLayout mAppBar;

    private MyShelfDetailFragment mParentFragment;
    private ArrayList<NewDigest> mDataList = new ArrayList<NewDigest>();
    private BookDigestMeAdapter mDigestMeAdapter;
    private HeaderAndFooterRecyclerViewAdapter mHeaderAndFooterRecyclerViewAdapter = null;

    private boolean mTypeMe = false;
    private int mWhereFrom;
    private int mVerticalOffset;
    private long bookId;

    private String mBookname;
    private Handler mHandler = new Handler();
    private String pageFrom = "";
    private boolean mChangedTab;

    private int mBaseBottomHeight; // 用于弹出键盘列表位移
    private int mKeyboardSize;
    private View mRootView;
    private boolean mIsOpenKeyborad;
    private boolean mIsLastPos; // 点击的是否是最后一个

    public static MyBookDigestFragment newInstance(long bookId, String bookname, int whereFrom) {
        MyBookDigestFragment fragment = new MyBookDigestFragment();
        Bundle args = new Bundle();
        args.putInt(Constants.ARG_FROM_WHERE, whereFrom);
        args.putLong(Constants.ARG_BOOK_ID, bookId);
        args.putString(Constants.ARG_BOOK_TITLE, bookname);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            bookId = getArguments().getLong(Constants.ARG_BOOK_ID);
            mWhereFrom = getArguments().getInt(Constants.ARG_FROM_WHERE);
            mBookname = getArguments().getString(Constants.ARG_BOOK_TITLE);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mRootView = inflater.inflate(R.layout.fragment_digest_list_new, container, false);
        ButterKnife.bind(this, mRootView);
        return mRootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //        自动刷新一次
        ptrRefresh.postDelayed(new Runnable() {
            @Override
            public void run() {
                ptrRefresh.autoRefresh(true);
            }
        }, 400);
    }

    @Override
    protected void initUI(View view) {
        super.initUI(view);
        mParentFragment = (MyShelfDetailFragment) getParentFragment();
        //        初始化刷新
        setRefresh();

        mDigestMeAdapter = new BookDigestMeAdapter(getActivity(), mBookname, mDataList, mWhereFrom);
        mHeaderAndFooterRecyclerViewAdapter = new HeaderAndFooterRecyclerViewAdapter(mDigestMeAdapter);
        recyclerView.setAdapter(mHeaderAndFooterRecyclerViewAdapter);
        recyclerView.getRecyclerView().setOverScrollMode(View.OVER_SCROLL_NEVER);

        //setLayoutManager
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(manager);

        // 默认隐藏，刷新后无数据的话才显示
        recyclerView.getEmptyView().setVisibility(View.GONE);

        header_digist_bar.setVisibility(View.GONE);
        initListener();
    }

    /**
     * 初始化监听器
     */

    private void initListener() {
        mAppBar.addOnOffsetChangedListener(this);
        recyclerView.setOnScrollListener(mOnScrollListener);

        mRootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect r = new Rect();
                mRootView.getWindowVisibleDisplayFrame(r);
                int screenHeight = mRootView.getRootView().getHeight();
                int heightDifference = screenHeight - (r.bottom - r.top);

                heightDifference -= r.top;
                // 过滤已经展开
                if (!mIsOpenKeyborad) {
                    return;
                }

                if (heightDifference >= mKeyboardSize) {
                    mKeyboardSize = heightDifference;
                    // 获得屏幕高度
                    WindowManager wm = getActivity().getWindowManager();
                    int screenHeightReal = wm.getDefaultDisplay().getHeight();

                    // 获得点击控件的所在屏幕的高度(底部为准) mBaseBottomHeight
                    // 计算 1. 获得键盘顶部 和 item底部的偏移量
                    int keyboardTopHeightInParent = screenHeightReal - heightDifference;
                    int offset = - (keyboardTopHeightInParent - scb_comment_bar.getHeight() - mBaseBottomHeight);

                    // 如果点击是最后一个并且差值是负值(即还需要向下面滚，则自动过滤)
                    if (mIsLastPos && offset < 0) {
                        return;
                    }

                    mParentFragment.hideFab();
                    recyclerView.getRecyclerView().scrollBy(0, offset);
                }
            }
        });

        /**
         * 触摸关闭评论条
         */
        recyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                //隐藏键盘
                if (event.getAction() == MotionEvent.ACTION_DOWN && scb_comment_bar.getVisibility() == View.VISIBLE) {
                    scb_comment_bar.setVisibility(View.GONE);
                    mIsOpenKeyborad = false;
                    Utils.closeInputMethod(getActivity(), scb_comment_bar.getEditText());
                }
                return false;
            }
        });

        header_digist_bar.setOnBarItemClickListener(new OnBarItemClickListener() {
            @Override
            public void onClick(int index, boolean desc, int previousIndex) {
                // 判断是否是我的
                mTypeMe = (index == HeaderDigestBarLayout.INDEX_ME);
                onRefresh(true);
            }
        });


        scb_comment_bar.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });
        // 发送条 发送按钮点击监听
        /*scb_comment_bar.setOnSendButtonClickListener(new OnSendButtonClickListener() {
            @Override
            public void onSend(Object obj, String content) {
                // 发送digest的评论
                try {
                    NewDigest digest = (NewDigest) obj;
                    reqSendDigestComment(digest, content);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onSend(Object obj, NewComment replyComment, String content) {
                // 弹出键盘
                mParentFragment.hideFab();
                Utils.showSoftkeyboard(getActivity(), scb_comment_bar);
                // 回复评论
                try {
                    NewDigest digest = (NewDigest) obj;
                    reqReplyComment(digest, replyComment, content);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });*/


        // 我的
        /*mDigestMeAdapter.setOnSocialBarClickListener(new BookDigestMeAdapter.OnSocialBarClickListener() {
            @Override
            public void onCommentClick(final View v, final int position, NewDigest digest) {
                scb_comment_bar.setExcerpt(digest);
                scb_comment_bar.setExcerptReplyComment(null, null);
                scb_comment_bar.setVisibility(View.VISIBLE);
                scb_comment_bar.requestFocus();

                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        int location[] = new int[2];
                        ((LinearLayout) v.getParent().getParent()).getLocationOnScreen(location);
                        mBaseBottomHeight = location[1] + ((LinearLayout) v.getParent().getParent()).getHeight();
                        mIsOpenKeyborad = true;
                        mIsLastPos = (mDigestMeAdapter.getItemCount() == position + 1);
                        Utils.showSoftkeyboard(getActivity(), scb_comment_bar.getEditText());
                    }
                }, 100);
            }

            @Override
            public void onReplyCommentClick(final View v, final int parentPosition, int childPosition, NewDigest digest) {
                // 发送对评论的回复
                if (!Utils.isNullForList(digest.getComments())) {
                    NewComment replyComment = digest.getComments().get(childPosition);
                    scb_comment_bar.setExcerpt(null);
                    scb_comment_bar.setExcerptReplyComment(digest, replyComment);
                    scb_comment_bar.setVisibility(View.VISIBLE);
                    scb_comment_bar.requestFocus();
                }

                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        int location[] = new int[2];
                        ((RelativeLayout) v.getParent().getParent()).getLocationOnScreen(location);
                        mBaseBottomHeight = location[1] + ((RelativeLayout) v.getParent().getParent()).getHeight();
                        mIsOpenKeyborad = true;
                        mIsLastPos = (mDigestMeAdapter.getItemCount() == parentPosition + 1);
                        Utils.showSoftkeyboard(getActivity(), scb_comment_bar.getEditText());
                    }
                }, 100);
            }

            @Override
            public void onPraiseClick(boolean prePraise, NewDigest digest) {
                if (prePraise) {
                    reqPraise(digest);
                } else {
                    reqCancelPraise(digest);
                }
            }

            @Override
            public void onEdit(int position, NewDigest digest) {
                Intent in = new Intent(getActivity(), ModifyMyDigestActivity.class);
                ModifyMyDigestActivity.initArguments(in, "请选择书摘本", position, digest);
                startActivity(in);
            }

            @Override
            public void onDel(int position, NewDigest digest) {
                showDelDlg(position, digest);
            }
        });*/
    }

    /**
     * 删除书摘
     *
     * @param digest
     */
    private void showDelDlg(final int position, final NewDigest digest) {
        SimpleDialog dialog = new SimpleDialog(getActivity());
        dialog.setAnimationEnable(true);
        dialog.setTitle("删除书摘");
        dialog.setContentText("确认删除此条书摘?");
        dialog.setOnPositiveListener(getString(R.string.ok), new SimpleDialog.OnPositiveListener() {
            @Override
            public void onClick(SimpleDialog dialog) {
                dialog.dismiss();
                new RequestServerTask<BaseResponse>(BaseResponse.class, getActivity(), getString(R.string.commit_pls_wait)) {
                    @Override
                    protected String requestServer() {
                        Map<String, Object> params = new HashMap<String, Object>();
                        params.put("excerptId", digest.id);
                        return HttpUtil.post(API.DELETE_DIGEST, params);
                    }

                    @Override
                    protected void onSuccess(BaseResponse result) {
                        mDataList.remove(position);
                        mDigestMeAdapter.notifyDataSetChanged();

                        Intent in = new Intent(Constants.EVENT_DEL_BOOK_DIGEST);
                        in.putExtra(Constants.ARG_BOOK_ID, String.valueOf(bookId));
                        EventBus.getDefault().post(in);
                        Utils.showToast(getActivity().getString(R.string.delete_success));
                    }
                }.start();
            }
        })
        .setOnNegativeListener(getString(R.string.cancel), new SimpleDialog.OnNegativeListener() {
            @Override
            public void onClick(SimpleDialog dialog) {
                dialog.dismiss();
            }
        }).show();
    }

    /**
     * 取消收藏
     * @param digest
     */
    private void reqCancelCollect(final NewDigest digest) {
        new RequestServerTask<BaseResponse>(BaseResponse.class, getActivity(), getString(R.string.submit_loading)) {
            @Override
            protected String requestServer() {
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("excerptId", digest.id);
                return HttpUtil.post(API.DIGEST_CANCEL_COLLECT, params);
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                endRefreshing();
            }

            @Override
            protected void onSuccess(BaseResponse result) {
                digest.collect_info.favorite = false;
                // 刷新
                mDigestMeAdapter.notifyDataSetChanged();
            }
        }.start();
    }

    /**
     * 收藏
     * @param digest
     */
    private void reqCollect(final NewDigest digest) {
        new RequestServerTask<BaseResponse>(BaseResponse.class, getActivity(), getString(R.string.submit_loading)) {
            @Override
            protected String requestServer() {
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("excerptId", digest.id);
                return HttpUtil.post(API.DIGEST_COLLECT, params);
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                endRefreshing();
            }

            @Override
            protected void onSuccess(BaseResponse result) {
                digest.collect_info.favorite = true;
                // 刷新
                mDigestMeAdapter.notifyDataSetChanged();
            }
        }.start();
    }

    /**
     * 取消点赞
     * @param digest
     */
    private void reqCancelPraise(final NewDigest digest) {
        new RequestServerTask<BaseResponse>(BaseResponse.class, getActivity(), getString(R.string.submit_loading)) {
            @Override
            protected String requestServer() {
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("excerptId", digest.id);
                return HttpUtil.post(API.DIGEST_CANCEL_PRAISE, params);
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                endRefreshing();
            }

            @Override
            protected void onSuccess(BaseResponse result) {
                try {
                    digest.collect_info.plusone = false;
                    int praiseNum = Integer.parseInt(digest.getZan_num()) - 1;
                    digest.setZan_num(String.valueOf(praiseNum));
                } catch (Exception e) {
                    digest.setZan_num("0");
                } finally {
                    mDigestMeAdapter.notifyDataSetChanged();
                }
            }
        }.start();
    }

    /**
     * 点赞
     * @param digest
     */
    private void reqPraise(final NewDigest digest) {
        new RequestServerTask<BaseResponse>(BaseResponse.class, getActivity(), getString(R.string.submit_loading)) {
            @Override
            protected String requestServer() {
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("excerptId", digest.id);
                return HttpUtil.post(API.DIGEST_PRAISE, params);
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                endRefreshing();
            }

            @Override
            protected void onSuccess(BaseResponse result) {
                try {
                    digest.collect_info.plusone = true;
                    int praiseNum = Integer.parseInt(digest.getZan_num()) + 1;
                    digest.setZan_num(String.valueOf(praiseNum));
                } catch (Exception e) {
                    digest.setZan_num("1");
                } finally {
                    mDigestMeAdapter.notifyDataSetChanged();
                }
            }
        }.start();
    }


    private EndlessRecyclerOnScrollListener mOnScrollListener = new EndlessRecyclerOnScrollListener() {

        @Override
        public void onLoadNextPage(View view) {
            super.onLoadNextPage(view);
            //mParentFragment.hideFab();
            try {
                LoadingFooter.State state = RecyclerViewStateUtils.getFooterViewState(recyclerView.getRecyclerView());
                if (state == LoadingFooter.State.Loading) {
                    LogUtils.kLog().e("the state is Loading, just wait..");
                    return;
                }

                if (hasMore) {
                    // loading more
                    RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView.getRecyclerView(), Constants.PAGE_REQUEST_COUNT, LoadingFooter.State.Loading, null);
                    loadData(pageFrom);
                } else {
                    //the end
                    RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView.getRecyclerView(), Constants.PAGE_REQUEST_COUNT, LoadingFooter.State.TheEnd, null);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    private void setRefresh() {
        ptrRefresh.setResistance(2.0F);
        ptrRefresh.setRatioOfHeaderHeightToRefresh(1.0F);
        ptrRefresh.setDurationToClose(300);
        ptrRefresh.setDurationToCloseHeader(1000);
        ptrRefresh.setLoadingMinTime(500);
        ptrRefresh.setPullToRefresh(false);
        ptrRefresh.setKeepHeaderWhenRefresh(true);
        ptrRefresh.disableWhenHorizontalMove(true);
        ptrRefresh.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout ptrFrameLayout, View view, View view1) {
                boolean canbePullDown = mVerticalOffset == 0 && PtrDefaultHandler.checkContentCanBePulledDown(ptrFrameLayout, ((SuperRecyclerView) view).getRecyclerView(), view1);
                return canbePullDown;
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout ptrFrameLayout) {
                refresh();
            }
        });
    }

    @Override
    protected BaseResponse parseData(String data) {
        Gson gson = Global.getGson();
        return gson.fromJson(data, BookDigestListResponse.class);
    }

//Load and Refresh


    @Override
    public void refresh() {
        super.refresh();
        ptrRefresh.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (ptrRefresh != null && ptrRefresh.isRefreshing()) {
                    ptrRefresh.refreshComplete();
                }
            }
        }, 2000);
        onRefresh();
    }

    public void onRefresh() {
        pageFrom = "";
        loadData(pageFrom);
    }

    private void onRefresh(boolean isChangedTab) {
        mChangedTab = isChangedTab;
        //        自动刷新一次
        ptrRefresh.postDelayed(new Runnable() {
            @Override
            public void run() {
                ptrRefresh.autoRefresh(true);
            }
        }, 50);
    }

    private int mPage;
    private boolean hasMore = true;
    private View.OnClickListener mFooterClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView.getRecyclerView(), Constants.PAGE_REQUEST_COUNT, LoadingFooter.State.Loading, null);
            loadData(pageFrom);
        }
    };

    protected void loadData(final String page) {
        final String lastItemId = mDataList.size() == 0 ? "0" : mDataList.get(mDataList.size() - 1).id + "";
        final boolean isDesc = header_digist_bar.isDescOfCurrentItem();

        if (!NetworkUtils.isNetAvailable(getActivity())) {
            RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView.getRecyclerView(), Constants.PAGE_REQUEST_COUNT, LoadingFooter.State.NetWorkError, this.mFooterClick);
        } else {
            RecyclerViewStateUtils.setFooterViewState(recyclerView.getRecyclerView(), LoadingFooter.State.Loading);
            new RequestServerTask<BookDigestListResponse>(BookDigestListResponse.class) {
                @Override
                protected String requestServer() {
                    Map<String, Object> params = new HashMap<String, Object>();
                    params.put("bookId", bookId);
                    params.put("pageFrom", TextUtils.isEmpty(page) ? "" : pageFrom);
                    params.put("pageSize", Constants.PAGE_REQUEST_COUNT);
                    params.put("pageDirection", Constants.DESC); // 按时间降序

                    return HttpUtil.post(API.GET_PAGE_DIGEST_ME, params);
                }

                @Override
                protected void onPostExecute(String s) {
                    super.onPostExecute(s);
                    endRefreshing();
                }

                @Override
                protected void onSuccess(BookDigestListResponse result) {
                    //没有更多数据 不能加载更多
                    try {
                        pageFrom = result.page;
                        if (result.data == null) {
                            hasMore = false;
                            RecyclerViewStateUtils.setFooterViewState(recyclerView.getRecyclerView(), LoadingFooter.State.TheEnd);
                        } else {
                            RecyclerViewStateUtils.setFooterViewState(recyclerView.getRecyclerView(), LoadingFooter.State.Normal);
                            hasMore = true;
                            mPage++;
                            bindData(result, TextUtils.isEmpty(page));
                        }
                    } catch (Exception e) {
                        Utils.showToast(R.string.sys_err);
                    }
                }
            }.start();
        }
    }

    private void doResult(BookDigestListResponse result) {

    }

    public void endRefreshing() {
        if (ptrRefresh != null) {
            ptrRefresh.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (ptrRefresh != null) {
                        ptrRefresh.refreshComplete();
                    }
                }
            }, 500);
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.book_img:
                Utils.showToast(R.string.my_favourite_digest);
                break;
            case R.id.left_text:
                intent = new Intent(getActivity(), NewDigestActivity.class);
                startActivity(intent);
                break;
            case R.id.right_text:
                intent = new Intent(Constants.ACTION_MAIN_SWITCH);
                intent.putExtra(Constants.EXTRA_SWITCH_INDEX, 0);
                EventBus.getDefault().post(intent);
                break;
        }
    }

    @Override
    public void onEventMainThread(Intent intent) {
        super.onEventMainThread(intent);
        if (intent.getAction() == Constants.ACTION_SHELVES_FAVOURITE) {
        } else if (intent.getAction() == Constants.ACTION_BOOKSHELVES_REFRESH
                || intent.getAction() == Constants.ACTION_ADD_DIGEST_COMPLETE) {
            refresh();
        }


        // 编辑我的书摘
        if (Constants.EVENT_MODIFY_BOOK_DIGEST.equals(intent.getAction())) {
            int position = intent.getIntExtra(Constants.ARG_MODIFY_POSITION, -1);
            if (position == -1) return;
            NewDigest newDigest = (NewDigest) intent.getSerializableExtra(Constants.ARG_MODIFY_DIGEST);
            NewDigest digest = mDataList.get(position);
            digest.setContent(newDigest.getContent());
            digest.setScreenshot(newDigest.getScreenshot());
            digest.setNote(newDigest.getNote());
            digest.setNotebook_id(newDigest.getNotebook_id());
            digest.setPage_num(newDigest.getPage_num());
            digest.setPublish_state(newDigest.getPublish_state());
            digest.setMenu_id(newDigest.getMenu_id());
            digest.setMenu_info(newDigest.getMenu_info());
            mDigestMeAdapter.notifyDataSetChanged();
        }

    }


    @Override
    protected void addDataToList(BaseResponse response, boolean isNew) {
        BookDigestListResponse resp = (BookDigestListResponse) response;


        // 我的
        if (!handleLoginClick()) {
            return;
        }
        if (isNew) {
            mDigestMeAdapter.clear();
            mHeaderAndFooterRecyclerViewAdapter = new HeaderAndFooterRecyclerViewAdapter(mDigestMeAdapter);
            recyclerView.setAdapter(mHeaderAndFooterRecyclerViewAdapter);
        }
        mDigestMeAdapter.append(resp.data);
        mDigestMeAdapter.notifyDataSetChanged();
    }

    @Override
    protected void showEmptyView() {

    }

    @Override
    protected void hideEmptyView() {

    }

    @Override
    protected void setHasMore(boolean hasMore) {

    }

    /**
     * 请求发送书摘的评论
     *
     * @param replyComment
     */
    private void reqReplyComment(final NewDigest digest, final NewComment replyComment, final String content) {
        new RequestServerTask<SendCommentResponse>(SendCommentResponse.class) {
            @Override
            protected String requestServer() {
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("commentId", replyComment.id);
                params.put("content", content);
                return HttpUtil.post(API.REPLY_COMMENT, params);
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
            }

            @Override
            protected void onSuccess(SendCommentResponse result) {
                Utils.showToast("回复评论成功");

                // 添加数据 刷新界面
                List<NewComment> comments = digest.getComments();
                if (comments == null) {
                    comments = new ArrayList<NewComment>();
                }
                comments.add(result.data);

                if (mDigestMeAdapter != null) {
                    mDigestMeAdapter.notifyDataSetChanged();
                }
                mIsOpenKeyborad = false;
                Utils.closeInputMethod(getActivity(), scb_comment_bar.getEditText());
                scb_comment_bar.setVisibility(View.GONE);

                mParentFragment.setFabVisibility(View.GONE);
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mParentFragment.setFabVisibility(View.VISIBLE);
                        mParentFragment.showFab();
                    }
                }, 500);
            }
        }.start();
    }

    /**
     * 请求发送书摘的评论
     *
     * @param digest
     */
    private void reqSendDigestComment(final NewDigest digest, final String content) {
        new RequestServerTask<SendCommentResponse>(SendCommentResponse.class) {
            @Override
            protected String requestServer() {
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("excerptId", digest.id);
                params.put("content", content);
                return HttpUtil.post(API.SEND_DIGEST_COMMENT, params);
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
            }

            @Override
            protected void onSuccess(SendCommentResponse result) {
                Utils.showToast("书摘评论成功");

                // 添加数据 刷新界面
                List<NewComment> comments = digest.getComments();
                if (comments == null) {
                    comments = new ArrayList<NewComment>();
                }
                comments.add(result.data);

                if (mDigestMeAdapter != null) {
                    mDigestMeAdapter.notifyDataSetChanged();
                }
                mIsOpenKeyborad = false;
                Utils.closeInputMethod(getActivity(), scb_comment_bar.getEditText());
                scb_comment_bar.setVisibility(View.GONE);

                mParentFragment.setFabVisibility(View.GONE);
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mParentFragment.setFabVisibility(View.VISIBLE);
                        mParentFragment.showFab();
                    }
                }, 500);
            }
        }.start();
    }

    private void smoothMoveToPosition(int n) {
        if (true) {
            return;
        }
        LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getRecyclerView().getLayoutManager();
        int firstItem = layoutManager.findFirstVisibleItemPosition();
        int lastItem = layoutManager.findLastVisibleItemPosition();
        if (n <= firstItem ){
            recyclerView.getRecyclerView().smoothScrollToPosition(n);
        }else if ( n <= lastItem ){
            int top = recyclerView.getRecyclerView().getChildAt(n - firstItem).getTop();
            recyclerView.getRecyclerView().smoothScrollBy(0, top);
        }else{
            recyclerView.getRecyclerView().smoothScrollToPosition(n);
        }
    }

    private boolean handleLoginClick() {
        boolean isLogin = PersistenceUtils.isLogin();
        Intent in = null;
        // 已登录 跳转到ProfileActivity
        if (isLogin) {
            return true;
        }

        // 未登录 则跳转至登录界面，点击登录时需要返回到当前界面
        else {
            in = new Intent(getActivity(), NewLoginActivity.class);
            in.setAction(Constants.ACTION_GO_LOGIN);
            EventBus.getDefault().postSticky(in);
            //getActivity().startActivity(in);
            return false;
        }
    }

    public RecyclerView findRecyclerView() {
        return recyclerView.getRecyclerView();
    }

    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
        mVerticalOffset = verticalOffset;
    }
}
